#pragma once

#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <iostream>
#include <cstring>
#include <cerrno>
#include <vector>
#include <pthread.h>
#include "Log.hpp"
#include "InetAddr.hpp"
#include "nocopy.hpp"

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};

const static int default_t = -1;
class UdpServer : public nocopy
{
public:
    UdpServer(uint16_t &port)
    :_port(port), _isrunning(false), _sockfd(default_t)
    {
        pthread_mutex_init(&_user_lock, nullptr);
    }

    ~UdpServer()
    {
        pthread_mutex_destroy(&_user_lock);
    }

    void InitServer()
    {
        //创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            perror("socket create failed!");
            exit(SOCKET_ERROR);
        }
        //创建成功
        //填写地址结构体
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;//地址族
        local.sin_port = htons(_port);//端口号主机序列转网络序列
        //不推荐服务器绑定唯一一个ip
        local.sin_addr.s_addr = INADDR_ANY;
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());//字符串风格IP转4字节IP，且主机序列转网络序列
        //绑定套接字
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        //绑定成功返回0，-1是失败
        if (n != 0)
        {
            // lg.LogMessage(Fatal, "bind error, %d, %s\n", errno, strerror(errno));
            exit(BIND_ERROR);
        }
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
            InetAddr client(peer);
            auto info = client.Print();
            std::cout << "[" + info + "]" + ":" << buffer << std::endl;
            if (n > 0)
            {
                buffer[n] = 0;
                // InetAddr addr(peer);
                sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr*)&peer, len);
            }
        }
        _isrunning = false;
    }
private:
    int _sockfd;
    uint16_t _port;
    // std::string _ip;
    bool _isrunning;
    std::vector<InetAddr> _online_user;
    pthread_mutex_t _user_lock;
};